<template>
  <view class="category-container">
    <!-- 搜索框 -->
    <view class="search-box">
      <input 
        v-model="searchKeyword" 
        placeholder="搜索图书..." 
        class="search-input"
        @confirm="handleSearch"
      />
      <view class="icon-search" @click="handleSearch">
        <text>🔍</text>
      </view>
    </view>

    <!-- 分类内容 -->
    <view class="category-content">
      <!-- 左侧分类菜单 -->
      <scroll-view scroll-y class="category-menu">
        <view 
          v-for="category in categories" 
          :key="category.id"
          class="menu-item"
          :class="{ active: currentCategory === category.id }"
          @click="switchCategory(category.id)"
        >
          <text class="menu-text">{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view 
        scroll-y 
        class="category-list"
        :style="{ height: scrollViewHeight + 'px' }"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
      >
        <!-- 分类横幅 -->
        <view class="category-banner" v-if="currentCategoryData.banner">
          <image 
            :src="currentCategoryData.banner" 
            class="banner-image" 
            mode="aspectFill"
          />
        </view>
        
        <!-- 商品网格 -->
        <view class="books-section">
          <view class="section-header">
            <text class="section-title">{{ currentCategoryData.name }}</text>
            <text class="book-count">共{{ totalCount }}件商品</text>
          </view>
          
          <view class="books-grid">
            <view 
              v-for="book in categoryBooks" 
              :key="book.id"
              class="book-card"
              @click="goToDetail(book.id)"
            >
              <view class="book-cover-container">
                <image 
                  :src="book.cover" 
                  class="book-cover" 
                  mode="aspectFill"
                />
                <view v-if="book.stock === 0" class="sold-out-tag">售罄</view>
                <view v-else-if="book.discount" class="discount-tag">{{ book.discount }}折</view>
              </view>
              
              <view class="book-info">
                <text class="book-title">{{ book.title }}</text>
                <text class="book-author">{{ book.author }}</text>
                
                <view class="book-bottom">
                  <view class="price-section">
                    <text class="book-price">¥{{ book.price }}</text>
                    <text v-if="book.originalPrice" class="book-original-price">¥{{ book.originalPrice }}</text>
                  </view>
                  <text class="book-sales">已售{{ book.sales || 0 }}</text>
                </view>
              </view>
              
              <button 
                class="add-cart-btn"
                @click.stop="addToCart(book)"
                :disabled="book.stock === 0"
              >
                <text v-if="book.stock === 0">缺货</text>
                <text v-else>购</text>
              </button>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-container">
            <text class="loading-text">加载中...</text>
          </view>
          
          <!-- 没有更多数据 -->
          <view v-if="noMore" class="no-more-container">
            <text class="no-more-text">没有更多商品了</text>
          </view>
          
          <!-- 空状态 -->
          <view v-if="showEmpty" class="empty-container">
            <image src="/static/empty.png" class="empty-image" mode="aspectFit" />
            <text class="empty-text">该分类暂无商品</text>
            <button class="empty-btn" @click="goToHome">去首页逛逛</button>
          </view>
        </view>
        
        <!-- 底部占位区域 -->
        <view class="bottom-placeholder" :style="{ height: placeholderHeight + 'px' }"></view>
      </scroll-view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        v-for="tab in tabList" 
        :key="tab.pagePath"
        class="tab-item"
        :class="{ active: currentTab === tab.pagePath }"
        @click="switchTab(tab)"
      >
        <view class="tab-icon">
          <image 
            :src="currentTab === tab.pagePath ? tab.selectedIconPath : tab.iconPath" 
            class="icon"
            mode="aspectFit"
          />
          <view v-if="tab.pagePath === 'bookshelf' && unreadCount > 0" class="bookshelf-badge">
            <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
          </view>
        </view>
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      currentCategory: 1,
      categories: [
        { id: 1, name: '文学小说', banner: '/static/banner1.jpg' },
        { id: 2, name: '科技科普', banner: '/static/banner2.jpg' },
        { id: 3, name: '经济管理', banner: '/static/banner3.jpg' },
        { id: 4, name: '教育学习', banner: '/static/banner1.jpg' },
        { id: 5, name: '艺术设计', banner: '/static/banner2.jpg' },
        { id: 6, name: '生活休闲', banner: '/static/banner3.jpg' }
      ],
      categoryBooks: [],
      currentPage: 1,
      pageSize: 8,
      totalCount: 0,
      loading: false,
      refreshing: false,
      noMore: false,
      showEmpty: false,
      scrollViewHeight: 0,
      placeholderHeight: 0,
      
      // 底部导航相关数据
      currentTab: 'category',
      unreadCount: 0, // 书架未读数量
      tabList: [
        {
          pagePath: 'index',
          text: '首页',
          iconPath: '/static/tabbar/home.png',
          selectedIconPath: '/static/tabbar/home-active.png'
        },
        {
          pagePath: 'category',
          text: '分类',
          iconPath: '/static/tabbar/category.png',
          selectedIconPath: '/static/tabbar/category-active.png'
        },
        {
          pagePath: 'bookshelf',
          text: '书架',
          iconPath: '/static/tabbar/bookshelf.png',
          selectedIconPath: '/static/tabbar/bookshelf-active.png'
        },
        {
          pagePath: 'profile',
          text: '我的',
          iconPath: '/static/tabbar/profile.png',
          selectedIconPath: '/static/tabbar/profile-active.png'
        }
      ]
    }
  },
  computed: {
    currentCategoryData() {
      return this.categories.find(cat => cat.id === this.currentCategory) || {}
    }
  },
  onLoad(options) {
    if (options.categoryId) {
      this.currentCategory = parseInt(options.categoryId)
    }
    this.calcLayoutHeight()
    this.loadCategoryBooks(true)
    this.updateUnreadCount()
  },
  onShow() {
    this.updateUnreadCount()
  },
  onPullDownRefresh() {
    this.onRefresh()
  },
  onReachBottom() {
    this.loadMore()
  },
  onResize() {
    this.calcLayoutHeight()
  },
  methods: {
    // 计算布局高度
    calcLayoutHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      const tabBarHeight = 100 // 底部导航栏高度
      const searchBoxHeight = 110 // 搜索框区域高度
      
      // 内容区域高度 = 窗口高度 - 搜索框高度 - 底部导航栏高度
      this.scrollViewHeight = windowHeight - searchBoxHeight - tabBarHeight
      
      // 占位区域高度 = 底部导航栏高度 + 安全区域底部间距
      this.placeholderHeight = tabBarHeight + (systemInfo.safeAreaInsets?.bottom || 0)
    },
    
    async loadCategoryBooks(init = false) {
      if (this.loading) return
      
      this.loading = true
      
      if (init) {
        this.currentPage = 1
        this.noMore = false
        this.showEmpty = false
      }
      
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        const mockBooks = this.generateMockBooks()
        
        if (init) {
          this.categoryBooks = mockBooks
          this.totalCount = 36
        } else {
          this.categoryBooks = [...this.categoryBooks, ...mockBooks]
        }
        
        // 模拟分页逻辑
        if (this.currentPage >= 3) {
          this.noMore = true
        }
        
        this.showEmpty = this.categoryBooks.length === 0
        
      } catch (error) {
        console.error('加载分类图书失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
        uni.stopPullDownRefresh()
      }
    },

    async onRefresh() {
      this.refreshing = true
      await this.loadCategoryBooks(true)
    },

    async loadMore() {
      if (this.loading || this.noMore) return
      
      this.currentPage++
      await this.loadCategoryBooks(false)
    },

    switchCategory(categoryId) {
      if (this.currentCategory === categoryId) return
      
      this.currentCategory = categoryId
      this.loadCategoryBooks(true)
    },

    handleSearch() {
      if (this.searchKeyword.trim()) {
        uni.navigateTo({
          url: `/pages/search/search?keyword=${encodeURIComponent(this.searchKeyword)}`
        })
      } else {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
      }
    },

    addToCart(book) {
      if (book.stock === 0) return
      
      let cart = uni.getStorageSync('cart') || []
      const existingItem = cart.find(item => item.id === book.id)
      
      if (existingItem) {
        if (existingItem.quantity < book.stock) {
          existingItem.quantity += 1
        } else {
          uni.showToast({ 
            title: '库存不足', 
            icon: 'none'
          })
          return
        }
      } else {
        cart.push({
          id: book.id,
          title: book.title,
          price: book.price,
          cover: book.cover,
          stock: book.stock,
          quantity: 1,
          selected: true
        })
      }
      
      uni.setStorageSync('cart', cart)
      uni.showToast({ 
        title: '添加成功', 
        icon: 'success'
      })
    },

    // 更新书架未读数量
    updateUnreadCount() {
      const bookshelf = uni.getStorageSync('bookshelf') || []
      // 假设未读状态为 status === 'unread'
      this.unreadCount = bookshelf.filter(book => book.status === 'unread').length
      
      // 设置tabbar角标
      if (this.unreadCount > 0) {
        uni.setTabBarBadge({
          index: 2, // 书架在第三个位置
          text: this.unreadCount > 99 ? '99+' : this.unreadCount.toString()
        })
      } else {
        uni.removeTabBarBadge({ index: 2 })
      }
    },

    goToDetail(bookId) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${bookId}`
      })
    },
    
    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },

    generateMockBooks() {
      const bookTitles = {
        1: ['百年孤独', '活着', '围城', '平凡的世界'],
        2: ['时间简史', '人类简史', '未来简史', '物种起源'],
        3: ['穷查理宝典', '原则', '经济学原理', '聪明的投资者'],
        4: ['如何阅读一本书', '学习之道', '刻意练习', '认知天性'],
        5: ['艺术的故事', '美的历程', '设计中的设计', '色彩与光线'],
        6: ['断舍离', '小家越住越大', '料理的快乐', '睡眠革命']
      }
      
      const titles = bookTitles[this.currentCategory] || ['默认图书']
      
      return Array.from({ length: this.pageSize }, (_, i) => {
        const titleIndex = i % titles.length
        const hasDiscount = Math.random() > 0.7
        const originalPrice = hasDiscount ? (Math.random() * 50 + 30).toFixed(2) : null
        const price = originalPrice ? (originalPrice * 0.8).toFixed(2) : (Math.random() * 50 + 10).toFixed(2)
        
        return {
          id: Date.now() + i,
          title: `${titles[titleIndex]} ${i + 1}`,
          author: `作者${i + 1}`,
          price: price,
          originalPrice: originalPrice,
          stock: Math.floor(Math.random() * 100),
          sales: Math.floor(Math.random() * 1000),
          cover: `/static/book${(i % 4) + 1}.jpg`,
          category: this.currentCategory,
          discount: hasDiscount ? 8 : null
        }
      })
    },

    switchTab(tab) {
      if (this.currentTab === tab.pagePath) return
      
      const pageMap = {
        'index': '/pages/index/index',
        'category': '/pages/category/category',
        'bookshelf': '/pages/bookshelf/bookshelf',
        'profile': '/pages/profile/profile'
      }
      
      const targetUrl = pageMap[tab.pagePath]
      if (targetUrl) {
        uni.switchTab({
          url: targetUrl,
          fail: (err) => {
            console.error('跳转失败:', err)
            uni.redirectTo({
              url: targetUrl
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.category-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8f8f8;
}

.search-box {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  height: 110rpx;
  box-sizing: border-box;
}

.search-input {
  flex: 1;
  height: 70rpx;
  background: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
}

.icon-search {
  padding: 10rpx;
  font-size: 36rpx;
  flex-shrink: 0;
}

.category-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.category-menu {
  width: 200rpx;
  background: #f8f8f8;
  flex-shrink: 0;
}

.menu-item {
  padding: 30rpx 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
  position: relative;
  
  &.active {
    background: #fff;
    
    .menu-text {
      color: #ff6b6b;
      font-weight: 600;
    }
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 40rpx;
      background: #ff6b6b;
      border-radius: 0 4rpx 4rpx 0;
    }
  }
}

.menu-text {
  font-size: 28rpx;
  color: #333;
}

.category-list {
  flex: 1;
  background: #fff;
}

.category-banner {
  padding: 30rpx;
}

.banner-image {
  width: 100%;
  height: 200rpx;
  border-radius: 16rpx;
  background: #f5f5f5;
  display: block;
}

.books-section {
  padding: 0 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.book-count {
  font-size: 24rpx;
  color: #999;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  padding-bottom: 30rpx;
}

.book-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  position: relative;
}

.book-cover-container {
  position: relative;
  width: 100%;
  padding-top: 140%; /* 5:7 比例 */
  background: #f5f5f5;
  overflow: hidden;
}

.book-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
}

.sold-out-tag, .discount-tag {
  position: absolute;
  top: 12rpx;
  left: 12rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  font-weight: 600;
  line-height: 1;
  z-index: 2;
}

.sold-out-tag {
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
}

.discount-tag {
  background: #ff6b6b;
  color: #fff;
}

.book-info {
  padding: 20rpx;
}

.book-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8rpx;
  min-height: 78rpx;
}

.book-author {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
  display: block;
}

.book-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.book-price {
  font-size: 32rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.book-original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.book-sales {
  font-size: 22rpx;
  color: #999;
}

.add-cart-btn {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  background: #ff6b6b;
  color: #fff;
  border-radius: 50%;
  border: none;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  
  &[disabled] {
    background: #ccc;
  }
}

.loading-container,
.no-more-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
}

.loading-text,
.no-more-text {
  font-size: 28rpx;
  color: #999;
}

.empty-container {
  flex-direction: column;
  padding: 120rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.empty-btn {
  background: #ff6b6b;
  color: #fff;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
  border: none;
}

.bottom-placeholder {
  width: 100%;
}

/* 底部导航栏样式 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  z-index: 999;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
  
  &.active {
    .tab-text {
      color: #ff6b6b;
    }
  }
}

.tab-icon {
  position: relative;
  margin-bottom: 8rpx;
}

.icon {
  width: 44rpx;
  height: 44rpx;
  display: block;
}

.bookshelf-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff6b6b;
  border-radius: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.badge-text {
  color: #fff;
  font-size: 20rpx;
  line-height: 1;
}

.tab-text {
  font-size: 22rpx;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 360px) {
  .books-grid {
    grid-template-columns: 1fr;
    gap: 20rpx;
  }
  
  .category-menu {
    width: 180rpx;
  }
}

@media (min-width: 414px) {
  .books-grid {
    gap: 30rpx;
  }
}

@media (min-width: 768px) {
  .books-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>
